import {defineStore, acceptHMRUpdate} from 'pinia';
import ReconnectingWebSocket from 'reconnecting-websocket';
import {TypeRTCConfig, Wss} from "src/utils/type";
declare type WssConnect = {
  close:Function
  onmessage:Function
  send:Function
}
interface State {
  wssConnect: WssConnect | {}
  wssMessage: Wss | {}
  isWindows:Boolean
  loginState:boolean
  channelName:string
  userInfo:{},
  crowdId:string
  RTMlog:Array<Object>,
  boardConfig:{},
  aliConfig:{},
  RTCConfig:TypeRTCConfig,
  behaviorId:string
}

export const useSysStore = defineStore('sysStores', {
  state: ():State => ({
    isWindows: false,
    loginState: true,
    userInfo: {},
    wssConnect:{},
    wssMessage:{},
    crowdId:'',
    RTMlog:[],
    RTCConfig: {} as TypeRTCConfig,
    channelName:'',
    boardConfig:{},
    aliConfig:{},
    behaviorId:'',  //行为ID
    fromAgent: false, //是否来自客服
  }),


  actions: {
    connectWss() {
      let token: string | null = localStorage.getItem('token');
      let wssUrl = 'wss://www.flopsai.cn:5087/user/ws?token='
      // let wssUrl = 'ws://112.192.23.17:5079/user/ws?token='
      this.wssConnect.close && this.wssConnect.close();
      this.wssConnect = new ReconnectingWebSocket(wssUrl + token, [], {
        maxRetries: 2   // 最大重连次数（默认为无限次）
      });
      this.wssConnect.onmessage = (event: {data:any}) => {
        this.wssMessage = JSON.parse(event.data)
        // this.wssMessage = event.data;
        // this.handleWssMessage(JSON.parse(event.data))
      }
      this.wssConnect.onclose = (msg) => {
        return console.error(msg);
      }
    },
    sendWss(para: any) {
      if (this.RTCConfig.channel_instance_id)
        para['channel_instance_id'] = this.RTCConfig.channel_instance_id;
      this.wssConnect.send && this.wssConnect.send(JSON.stringify(para));
    },
    clear() {
      this.userInfo = {};
      this.wssConnect = {};
      this.wssMessage = {};
    }
  },
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useSysStore, import.meta.hot));
}
